package site.anxuan.seckill.configuration;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import site.anxuan.seckill.interceptor.LoginInterceptor;
import site.anxuan.seckill.property.WebProperty;

import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(WebProperty.class)
public class WebMvcConfiguration implements WebMvcConfigurer {

    private final WebProperty webProperty;

    private final LoginInterceptor loginInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(webProperty.getPath())
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> interceptPaths = new ArrayList<>();
        interceptPaths.add("/order/create");
        interceptPaths.add("/order/captcha");
        registry.addInterceptor(loginInterceptor).addPathPatterns(interceptPaths);
    }

}
